package xps.and.uudaijia.userclient.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.jude.utils.JUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import rx.Subscriber;
import xps.and.uudaijia.userclient.Constants;
import xps.and.uudaijia.userclient.data.baen.LoginBean;
import xps.and.uudaijia.userclient.data.net.UserNetWorks;
import xps.and.uudaijia.userclient.util.Util;
import xps.and.uudaijia.userclient.view.activity.BinDingActivity;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final String TAG = "WXEntryActivity";
    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;
    String openid;
    String nickname;
    int sex;
    String language;
    String city;
    String province;
    String country;
    String headimgurl;
    String unionid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);
        api.handleIntent(intent, this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq baseReq) {
        Log.i(TAG, baseReq.toString());
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (resp instanceof SendAuth.Resp) {
                    String code = ((SendAuth.Resp) resp).code;
                    String state = ((SendAuth.Resp) resp).state;

                    String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constants.APP_ID + "&secret=" + Constants.SECRET + "&code=" + code + "&grant_type=authorization_code";
                    new GetAccessTokenTask().execute(url);
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                break;
            default:
                break;
        }

        finish();
    }

    private class GetAccessTokenTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
            try {
                return Util.httpGet(urls[0]);
            } catch (IOException e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (result == null) {
                Toast.makeText(WXEntryActivity.this, "连接出错，请检查网络是否已连接", Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                JSONObject jsonObject = new JSONObject(result);
                String access_token = jsonObject.optString("access_token");
                int expires_in = jsonObject.optInt("expires_in");
                String refresh_token = jsonObject.optString("refresh_token");
                String openid = jsonObject.optString("openid");
                String scope = jsonObject.optString("scope");
                String unionid = jsonObject.optString("unionid");
                String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid;
                new GetUserInfoTask().execute(url);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private class GetUserInfoTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
            try {
                return Util.httpGet(urls[0]);
            } catch (IOException e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (result == null) {
                Toast.makeText(WXEntryActivity.this, "连接出错，请检查网络是否已连接", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                JSONObject jsonObject = new JSONObject(result);
                openid = jsonObject.optString("openid");
                nickname = jsonObject.optString("nickname");
                sex = jsonObject.optInt("sex");
                language = jsonObject.optString("language");
                city = jsonObject.optString("city");
                province = jsonObject.optString("province");
                country = jsonObject.optString("country");
                headimgurl = jsonObject.optString("headimgurl");
                unionid = jsonObject.optString("unionid");
                Login();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    void Login() {
        UserNetWorks.getWechatLogin("oauth", openid, nickname, String.valueOf(sex), headimgurl, country, province, city, new Subscriber<LoginBean>() {

            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(LoginBean loginBean) {
                LoginBean.ReturnBodyBean returnBodyBean = loginBean.getReturn_body();
                if (loginBean.getReturn_code().equals("SUCCESS")) {
                    SharedPreferences sp = JUtils.getSharedPreference();
                    SharedPreferences.Editor spEd = sp.edit();
                    spEd.putString("User_Access_token", returnBodyBean.getAccess_token());
                    spEd.putString("User_ID", returnBodyBean.getUserId() + "");
                    spEd.putString("User_name", returnBodyBean.getName() + "");
                    spEd.putString("User_Img", returnBodyBean.getHeadImg() + "");
                    spEd.putString("YHJ", "");
                    spEd.commit();
                    Intent intent = new Intent(WXEntryActivity.this, BinDingActivity.class);
                    startActivity(intent);
                } else if (loginBean.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(loginBean.getReturn_msg());
                }

            }
        });
    }
}
